package com.hong.utils.executors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Auther: Administrator
 * @Date: 2018/7/26 20:02
 * @Description:
 * 测试
 * newSingleThreadExecutor
 * newFixedThreadPool
 * newCachedThreadPool的区别
 */
public class ExecutorsExample1 {
    public static void main(String[] args) throws InterruptedException {
//        useCacheThreadPool();
//        useFixedSizePool();
        useSinglePool();
    }


    /**
     * SingleThreadExecutor diffrence between one Thread.
     */
    private static void useSinglePool() throws InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());
        IntStream.range(0,10).boxed().forEach(i->executorService.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"["+i+"]");
        }));
        TimeUnit.SECONDS.sleep(1);
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());

    }

    private static void useFixedSizePool() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());
        IntStream.range(0,10).boxed().forEach(i->executorService.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"["+i+"]");
        }));
        TimeUnit.SECONDS.sleep(1);
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());
    }

    private static void useCacheThreadPool() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());

        executorService.execute(()-> System.out.println("======================"));
        IntStream.range(0,100).boxed().forEach(i->executorService.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"["+i+"]");
        }));
        TimeUnit.SECONDS.sleep(1);
        System.out.println(((ThreadPoolExecutor)executorService).getActiveCount());
    }
}
